import sys
sys.path.append("../")
from services.DayKlineService import *
from frameworks.utils.RedisUtil import *

class ScoreCalcController:
    def __init__(self,args={}):
        self.klineService = DayKlineService()
        self.redis = RedisUtil()
        self.args = args

    def calcScore(self,code,startDay,endDay):
        data = self.klineService.getThirtyDataByEnd(code,startDay,endDay)
        score = 0
        moneyscore = 0
        money_zf = 0
        n = 1
        zf = 0
        for row in data:
            # 计算涨幅分数
            close = float(row["close"])
            if row["pre_close"] == None:
                n += 1
                continue
            pre = float(row["pre_close"])
            zf = round(((close - pre) * 100) / pre, 2)
            score += zf * n

            money = float(row["money"])
            flow_money = close * float(row["flow_volume"])
            if flow_money > 0:
                if close > pre:
                    money_zf = round((money * 100) / flow_money, 2)
                else:
                    money_zf = -1 * round((money * 100) / flow_money, 2)
                moneyscore += money_zf * n
            n += 1
        return [round(score, 2), round(zf, 2), round(moneyscore, 2), round(money_zf, 2)]

    def calcOrder(self,startDay,endDay,calcDay):
        codelist = self.klineService.getTenHasZhangtingByDate(startDay,endDay)
        objlist = []
        for row in codelist:
            score,zf,money_score,money_zf = self.calcScore(row["code"],calcDay,endDay)
            objlist.append({
                "code": row["code"],
                "codename": row["codename"],
                "score": score,
                "zf": zf,
                "money": str(round(row["flow_money"] / 100000000)) + " 亿元",
                "money_score": money_score,
                "money_zf": money_zf,
                "industry": row["industry"]
            })

        scorelist = reversed(sorted(objlist, key=lambda x: x['score']))
        ordScore = {}
        m = 0
        for obj in scorelist:
            ordScore[obj["code"]] = m
            m += 1

        moneyscorelist = reversed(sorted(objlist, key=lambda x: x['money_score']))
        n = 0
        moneyScore = {}
        for obj in moneyscorelist:
            moneyScore[obj["code"]] = n
            n += 1

        allScorelist = {}
        for key in ordScore.keys():
            allScorelist[key] = ordScore[key] + moneyScore[key]

        optionlist = []
        for row in objlist:
            row["allscore"] = allScorelist[row["code"]]
            optionlist.append(row)

        ck = "score_calc_controller"
        self.redis.vset(ck,json.dumps(objlist))

        return optionlist